﻿using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;

namespace SharpGL.Media3D
{
    [TypeConverter(typeof(ExpandableObjectConverter))]
    [DataContract(/*IsReference = true, */Name = "Size3D", Namespace = "SharpGL")]
    public struct Size3D : IFormattable
    {
        #region Private Fields

        [DataMember()]
        private float x;

        [DataMember()]
        private float y;

        [DataMember()]
        private float z;

        private readonly static Size3D s_empty = CreateEmptySize3D();

        #endregion Private Fields

        #region Private Methods

        private static Size3D CreateEmptySize3D()
        {
            Size3D empty = new Size3D(); 
            // Can't use setters because they throw on negative values
            empty.x = float.NegativeInfinity; 
            empty.y = float.NegativeInfinity; 
            empty.z = float.NegativeInfinity;

            return empty; 
        }

        /// <summary>
        /// Helper to get the numeric list separator for a given IFormatProvider.
        /// Separator is a comma [,] if the decimal separator is not a comma, or a semicolon [;] otherwise. 
        /// </summary>
        static private char GetNumericListSeparator(IFormatProvider provider)
        {
            char numericSeparator = ',';

            // Get the NumberFormatInfo out of the provider, if possible
            // If the IFormatProvider doesn't not contain a NumberFormatInfo, then 
            // this method returns the current culture's NumberFormatInfo. 
            NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider);
            Debug.Assert(null != numberFormat);

            // Is the decimal separator is the same as the list separator?
            // If so, we use the ";". 
            if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numericSeparator == numberFormat.NumberDecimalSeparator[0]))
            {
                numericSeparator = ';';
            }

            return numericSeparator;
        }

        /// <summary>
        /// Creates a string representation of this object based on the format string 
        /// and IFormatProvider passed in.
        /// If the provider is null, the CurrentCulture is used. 
        /// See the documentation for IFormattable for more information. 
        /// </summary>
        /// <returns> 
        /// A string representation of this object.
        /// </returns>
        internal string ConvertToString(string format, IFormatProvider provider)
        {
            if (IsEmpty)
            {
                return "Empty";
            }

            // Helper to get the numeric list separator for a given culture.
            char separator = GetNumericListSeparator(provider);
            return String.Format(provider,
                                 "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}",
                                 separator,
                                 x,
                                 y,
                                 z);
        }

        #endregion Private Methods

        #region Constructors

        /// <summary> 
        /// Constructor which sets the size's initial values.  Values must be non-negative.
        /// </summary> 
        /// <param name="x">X dimension of the new size.</param>
        /// <param name="y">Y dimension of the new size.</param>
        /// <param name="z">Z dimension of the new size.</param>
        public Size3D(float x, float y, float z) 
        {
            if (x < 0 || y < 0 || z < 0) 
            { 
                throw new System.ArgumentException("Dimension cannot be negative");
            }

            this.x = x;
            this.y = y;
            this.z = z;
        } 

        #endregion Constructors

        #region Public Methods

        /// <summary>
        /// Compares two Size3D instances for object equality.  In this equality 
        /// Double.NaN is equal to itself, unlike in numeric equality.
        /// Note that double values can acquire error when operated upon, such that
        /// an exact comparison between two values which
        /// are logically equal may fail. 
        /// </summary>
        /// <param name="size1">The first Size3D to compare</param> 
        /// <param name="size2">The second Size3D to compare</param>
        /// <returns> 
        /// bool - true if the two Size3D instances are exactly equal, false otherwise 
        /// </returns>
        public static bool Equals(Size3D size1, Size3D size2)
        {
            if (size1.IsEmpty)
            {
                return size2.IsEmpty;
            }
            else
            {
                return size1.X.Equals(size2.X) &&
                       size1.Y.Equals(size2.Y) &&
                       size1.Z.Equals(size2.Z);
            }
        }

        /// <summary> 
        /// Equals - compares this Size3D with the passed in object.  In this equality
        /// Double.NaN is equal to itself, unlike in numeric equality. 
        /// Note that double values can acquire error when operated upon, such that
        /// an exact comparison between two values which
        /// are logically equal may fail.
        /// </summary> 
        /// <param name="o">The object to compare to "this"</param>
        /// <returns>
        /// bool - true if the object is an instance of Size3D and if it's equal to "this". 
        /// </returns> 
        public override bool Equals(object o)
        {
            if ((null == o) || !(o is Size3D))
            {
                return false;
            }

            Size3D value = (Size3D)o;
            return Size3D.Equals(this, value);
        }

        /// <summary>
        /// Equals - compares this Size3D with the passed in object.  In this equality
        /// Double.NaN is equal to itself, unlike in numeric equality. 
        /// Note that double values can acquire error when operated upon, such that
        /// an exact comparison between two values which 
        /// are logically equal may fail. 
        /// </summary>
        /// <param name="value">The Size3D to compare to "this"</param>
        /// <returns> 
        /// bool - true if "value" is equal to "this".
        /// </returns>
        public bool Equals(Size3D value)
        {
            return Size3D.Equals(this, value);
        }

        /// <summary>
        /// Returns the HashCode for this Size3D 
        /// </summary>
        /// <returns>
        /// int - the HashCode for this Size3D
        /// </returns> 
        public override int GetHashCode()
        {
            if (IsEmpty)
            {
                return 0;
            }
            else
            {
                // Perform field-by-field XOR of HashCodes 
                return X.GetHashCode() ^
                       Y.GetHashCode() ^
                       Z.GetHashCode();
            }
        }

        /// <summary>
        /// Creates a string representation of this object based on the current culture. 
        /// </summary> 
        /// <returns>
        /// A string representation of this object. 
        /// </returns>
        public override string ToString()
        {
            // Delegate to the internal method which implements all ToString calls.
            return ConvertToString(null /* format string */, null /* format provider */);
        }

        /// <summary> 
        /// Creates a string representation of this object based on the IFormatProvider
        /// passed in.  If the provider is null, the CurrentCulture is used.
        /// </summary>
        /// <returns> 
        /// A string representation of this object.
        /// </returns> 
        public string ToString(IFormatProvider provider)
        {
            // Delegate to the internal method which implements all ToString calls.
            return ConvertToString(null /* format string */, provider);
        }

        /// <summary>
        /// Creates a string representation of this object based on the format string 
        /// and IFormatProvider passed in. 
        /// If the provider is null, the CurrentCulture is used.
        /// See the documentation for IFormattable for more information. 
        /// </summary>
        /// <returns>
        /// A string representation of this object.
        /// </returns> 
        string IFormattable.ToString(string format, IFormatProvider provider)
        {
            // Delegate to the internal method which implements all ToString calls.
            return ConvertToString(format, provider);
        }

        #endregion Public Methods

        #region Public Operators

        /// <summary>
        /// Compares two Size3D instances for exact equality.
        /// Note that double values can acquire error when operated upon, such that 
        /// an exact comparison between two values which are logically equal may fail.
        /// Furthermore, using this equality operator, Double.NaN is not equal to itself. 
        /// </summary> 
        /// <param name="size1">The first Size3D to compare</param>
        /// <param name="size2">The second Size3D to compare</param>
        /// <returns>
        /// bool - true if the two Size3D instances are exactly equal, false otherwise 
        /// </returns>
        public static bool operator ==(Size3D size1, Size3D size2)
        {
            return size1.X == size2.X &&
                   size1.Y == size2.Y &&
                   size1.Z == size2.Z;
        }

        /// <summary>
        /// Compares two Size3D instances for exact inequality.
        /// Note that double values can acquire error when operated upon, such that 
        /// an exact comparison between two values which are logically equal may fail.
        /// Furthermore, using this equality operator, Double.NaN is not equal to itself. 
        /// </summary> 
        /// <param name="size1">The first Size3D to compare</param>
        /// <param name="size2">The second Size3D to compare</param>
        /// <returns>
        /// bool - true if the two Size3D instances are exactly unequal, false otherwise 
        /// </returns>
        public static bool operator !=(Size3D size1, Size3D size2)
        {
            return !(size1 == size2);
        }

        #endregion Public Operators

        #region Public Properties

        /// <summary>
        /// Empty - a static property which provides an Empty size.  X, Y, and Z are 
        /// negative-infinity.  This is the only situation
        /// where size can be negative. 
        /// </summary> 
        public static Size3D Empty
        {
            get
            {
                return s_empty;
            }
        }
        
        /// <summary>
        /// IsEmpty - this returns true if this size is the Empty size.
        /// Note: If size is 0 this Size3D still contains a 0, 1, or 2 dimensional set 
        /// of points, so this method should not be used to check for 0 volume.
        /// </summary> 
        public bool IsEmpty
        {
            get
            {
                return x < 0;
            }
        }

        /// <summary> 
        /// Size in X dimension. Default is 0, must be non-negative. 
        /// </summary>
        public float X 
        {
            get
            {
                return x; 
            }
            set
            { 
                if (IsEmpty)
                { 
                    throw new System.InvalidOperationException("Cannot modify empty size");
                }

                if (value < 0) 
                {
                    throw new System.ArgumentException("Dimension cannot be negative"); 
                } 

                x = value; 
            }
        }

        /// <summary> 
        /// Size in Y dimension. Default is 0, must be non-negative.
        /// </summary> 
        public float Y 
        {
            get
            {
                return y;
            }
            set
            {
                if (IsEmpty) 
                { 
                    throw new System.InvalidOperationException("Cannot modify empty size");
                } 

                if (value < 0)
                {
                    throw new System.ArgumentException("Dimension cannot be negative"); 
                }

                y = value; 
            }
        } 

        /// <summary>
        /// Size in Z dimension. Default is 0, must be non-negative. 
        /// </summary>
        public float Z 
        { 
            get
            { 
                return z;
            }
            set
            { 
                if (IsEmpty)
                { 
                    throw new System.InvalidOperationException("Cannot modify empty size"); 
                }

                if (value < 0)
                {
                    throw new System.ArgumentException("Dimension cannot be negative");
                } 

                z = value; 
            } 
        }

        #endregion Public Methods
    }
}
